package com.lczc.soa.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtils {
    private final static  Logger log = LoggerFactory.getLogger(IPUtils.class);
    /**
     * X-Forwarded-For
     * X-Real-IP
     * Proxy-Client-IP
     * WL-Proxy-Client-IP
     * HTTP_CLIENT_IP
     * HTTP_X_FORWARDED_FOR
     * getRemoteAddr()
     * @param request
     * @return String
     * 根据request得到真实的请求ip
     */
    public static String getRealRemoteIP(HttpServletRequest request)
    {
        String ip = request.getHeader("X-Forwarded-For");
//        log.debug("X-Forwarded-For ==>"+ip);
        if (!ifRealIP(ip)) {
            ip = request.getHeader("X-Real-IP");
//	      log.debug("X-Real-IP ==>"+ip);
        }
        if (!ifRealIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
//	      log.debug("Proxy-Client-IP ==>"+ip);
        }
        if (!ifRealIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
//	      log.debug("WL-Proxy-Client-IP ==>"+ip);
        }
        if (!ifRealIP(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
//	      log.debug("HTTP_CLIENT_IP ==>"+ip);
        }
        if (!ifRealIP(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//	    	log.debug("HTTP_X_FORWARDED_FOR ==>"+ip);
        }
        if (!ifRealIP(ip)) {
            ip = request.getRemoteAddr();
//	      log.debug("request.getRemoteAddr() ==>"+ip);
        }
        log.debug("RealRemoteIP ==>"+ip);
        return ip;
    }

    /**
     *
     * 校验是否为有效IP
     * @param ip
     * @return boolean
     */
    public static boolean ifRealIP(String ip)
    {
        if(StringUtils.isEmpty(ip)|| "unknown".equalsIgnoreCase(ip)||ip.length() < 7 || ip.length() > 15){
            return false;
        }
        //判断IP格式和范围
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";

        Pattern pat = Pattern.compile(rexp);

        Matcher mat = pat.matcher(ip);

        boolean ipAddress = mat.find();

        return ipAddress;
    }

}
